//
//  AppDelegate.swift
//  SinaWeibo
//
//  Created by yang on 15/11/8.
//  Copyright © 2015年 yang. All rights reserved.
//

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        window = UIWindow(frame: UIScreen.mainScreen().bounds)
        window?.backgroundColor = UIColor.whiteColor()
        window?.makeKeyAndVisible()
        setTitleColor()
        registerNotification()
        window?.rootViewController = defaultRootController()
        return true
    }
    //监听通知,切换控制器
    private func registerNotification(){
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "switchToRootViewControler:", name: AppSwitchRootViewControler, object: nil)
    }
    //监听方法
    @objc private func switchToRootViewControler(notify:NSNotification){
        if (notify.object as? String) != nil {
            window?.rootViewController = WelComeViewController()
        }
        window?.rootViewController = MainViewController()
    }
    //移除通知
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    // 判断用户是否登陆 并且是否是更新版本
    private func defaultRootController() -> UIViewController{
        if UserAccountViewModel().userLogin{
            return isNewVersion() ?NewFeatureViewController():WelComeViewController()
        }
        return MainViewController()
    }
    //判断是不是新版本
    private func isNewVersion() -> Bool{
        let versionNow = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String
        let versionNum = Double(versionNow)
        let key = "version"
        let userdefaults = NSUserDefaults.standardUserDefaults()
        let versionLast = userdefaults.doubleForKey(key)
        userdefaults.setDouble(versionNum!, forKey: key)
        userdefaults.synchronize()
        return versionNum! > versionLast
    }
    //设置字体颜色
    func setTitleColor (){
        UINavigationBar.appearance().tintColor = titleColor
        UITabBar.appearance().tintColor = titleColor
    }
}

